<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <div class="demo-input-suffix">
 
        <el-input clearable @keyup.enter.native="handleFilter" v-model="listQuery.orderId" style="width: 200px;margin-right:15px;margin-top:7px" class="filter-item" placeholder="请输入订单编号" />
        <el-input clearable @keyup.enter.native="handleFilter" v-model="listQuery.nickName" style="width: 200px;margin-right:15px;margin-top:7px" class="filter-item" placeholder="请输入用户昵称" />
        <el-input clearable @keyup.enter.native="handleFilter" v-model="listQuery.batteryId" style="width: 200px;margin-right:15px;margin-top:7px" class="filter-item" placeholder="请输入充电宝ID" />
       
        <el-input clearable @keyup.enter.native="handleFilter" v-model="listQuery.usersPhone" style="width: 200px;margin-right:15px;margin-top:7px" class="filter-item" placeholder="请输入手机号码" />
      </div>
      <div class="demo-input-suffix">
        <el-input clearable @keyup.enter.native="handleFilter" v-model="listQuery.address" style="width: 200px;margin-right:15px;margin-top:7px" class="filter-item" placeholder="请输入借用地点" />
        <el-date-picker
          v-model="listQuery.date"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="timestamp">
        </el-date-picker>
        <el-select placeholder='支付方式' v-model="listQuery.payType" clearable>
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-select placeholder='订单状态' v-model="listQuery.orderStatus" clearable>
          <el-option
            v-for="item in status"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-button class="filter-item" type="primary" v-waves  icon="el-icon-search" @click="handleFilter" style="margin-bottom:0px;">{{$t('common.Search')}}</el-button>
        <el-button class="filter-item" type="primary" v-waves icon="el-icon-download" @click="handleDownload" style="margin-bottom:0px;" :loading="downloadLoading">{{$t('common.Export')}}</el-button>
        <!-- <el-button class="filter-item" style="margin-left: 10px;" v-waves type="primary" icon="el-icon-circle-plus-outline">添加</el-button> -->
      </div>
  </div>
    <!-- table 表格 -->
    <el-table  :data="list" v-loading="loading.list" :element-loading-text="$t('common.Loading')" border fit highlight-current-row
      style="width: 100%">
      <el-table-column  :label="$t('order.Number')" prop='index' />
      <el-table-column  :label="$t('order.Order_number')" prop='orderId' /> 
      <el-table-column  :label="$t('order.User_phone_number')" prop='usersPhone' />   
      <el-table-column  :label="$t('order.User_name')" prop='nickName' />  
      <el-table-column  :label="$t('order.Charging_treasure_ID')" prop='batteryId' />
      <el-table-column  :label="$t('order.Carbinet_number')" prop='equipmentId'/>
      <el-table-column  :label="$t('order.outTradeNo')" prop='outTradeNo'/>
      <el-table-column  :label="$t('order.Borrowing_place')" prop='businessAddress' />
       <el-table-column  :label="$t('order.Borrowing_time')" prop='leaseStartTime'>
        <template slot-scope="scope">
          <span v-if="scope.row.leaseStartTime">{{scope.row.leaseStartTime | parseTime}}</span>
           <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column  :label="$t('order.Returning_time')" prop='leaseEndTime'>
        <template slot-scope="scope">
          <span v-if="scope.row.leaseEndTime">{{scope.row.leaseEndTime | parseTime}}</span>
           <span v-else>-</span>
        </template>
      </el-table-column>
        <el-table-column  :label="$t('order.Service_time')" prop='useTime' />
       <el-table-column  :label="$t('order.Borrowing_fee')">
          <template slot-scope="scope">
             <div v-if="scope.row.totalPrice">{{ scope.row.totalPrice + $t('order.unit')}}</div>
             <div v-else>
               -
             </div>
          </template>
      </el-table-column>
      <el-table-column  :label="$t('order.Deducted_coupon')" prop='couponPrice'/>
      <el-table-column  :label="$t('order.Deducted_point')" prop='couponScore'/>
      <el-table-column  :label="$t('order.Actual_payment')">
          <template slot-scope="scope">
             <div v-if="scope.row.actualPrice">{{ scope.row.actualPrice + $t('order.unit')}}</div>
             <div v-else>
               -
             </div>
          </template>
      </el-table-column>
      <el-table-column  :label="$t('order.payment_method')">
        <template slot-scope="scope">
            <div>{{ scope.row.payType == 1 ? '余额' :scope.row.payType == 2 ? '微信': scope.row.payType == 3 ?'微信小程序': scope.row.payType == 4 ? '信用卡' : scope.row.payType == 5 ? '支付宝支付' : '-'}}</div>
        </template>
      </el-table-column>
      <el-table-column  :label="$t('order.Order_status')" prop="orderStatus">
          <template slot-scope="scope">
             <div>
               {{ 
                scope.row.isFlag == 1 && scope.row.orderStatus == 1 ? '未支付' : 
                scope.row.isFlag == 1 && scope.row.orderStatus == 2 ? '进行中' : 
                scope.row.isFlag == 1 && scope.row.orderStatus == 3 ? '已完成' : 
                scope.row.isFlag == 2 ? '已取消' : '-'}}
              </div>
          </template>
      </el-table-column>
      <el-table-column  :label="$t('order.Operate')"  class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <router-link :to="{name:'equipmentOrders_detail',query:{orderId:scope.row.orderId}}">
            <el-button   type='text'>{{$t('order.detail')}}
            </el-button>
          </router-link> 
          <el-button   type='text'  v-if="scope.row.orderStatus == 3" @click="cancalOrders(scope.row.orderId)">{{$t('order.Refund')}}
          </el-button>
          <el-button   type='text'  v-if="scope.row.orderStatus != 3" @click="endOrders(scope.row.orderId)">{{$t('order.Complete_order')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination 
      background 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
      :current-page="listQuery.pageNo" 
      :page-sizes="[10, 20, 30, 40]" 
      :page-size="listQuery.pageSize" 
      layout="total, sizes, prev, pager, next, jumper" 
      :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getOrdersList, endOrders , exportExcel, cancalOrders } from '@/api/equipmentOrders';
import { getdTime ,parseTime} from '@/utils/index'
export default {
  name: 'equipmentOrders_list',
  data() {
    return {
      total: 0,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        orderId: '',
        equipmentId:'',
        address: '',
        date: '',
        nickName: '',
        orderStatus: '',
        payType: ''
      },
      list: null,
      loading: {
        list: false,
        download: false
      },
      categoryList:[],
      options: [
        {
          value: '1',
          label: '余额',
          lang: 'order.Balance'
        }, {
          value: '2',
          label: '微信',
          lang: 'order.WeChat'
        }, {
          value: '3',
          label: '信用卡',
          lang: 'order.Credit_card'
        }
      ],
      status: [
        {
          value: '1',
          label: '未支付',
          lang: 'order.unpaid'
        },
        {
          value: '2',
          label: '进行中',
          lang: 'order.processing'
        },
        {
          value: '3',
          label: '已完成',
          lang: 'order.completed'
        },
        {
          value: '4',
          label: '已取消',
          lang: 'order.Cancelled'
        }
      ],
      downloadLoading:false
    }
  },
  methods: {
    //获取订单列表
    async getList() {
      this.loading.list = true
      try {
        let { date, ...query } = this.listQuery
        let [startTime, endTime] = date ? date : []
        query = Object.assign({}, query, {startTime, endTime})
        const { data } = await getOrdersList(query)
        this.list = data.records.map((item, index) =>{
          if(item.ruleParameter) {
            return {
              index: index + 1,
                ...item,
              useTime: getdTime(item.leaseStartTime, item.leaseEndTime),
              ruleParameters: JSON.parse(item.ruleParameter),
            }
          }else {
            return {
              index: index + 1,
                ...item,
                useTime: getdTime(item.leaseStartTime, item.leaseEndTime)
            }
          }
        })
        this.total = data.total
      } catch (error) {
        
      }
      this.loading.list = false
     
    },
    //结束订单
    async endOrders (orderId) {
      const {data} = await endOrders ({orderId})
            this.$message('订单结束成功');
            this.getList()
    },
    //退款(取消订单)
    async cancalOrders(orderId) {
       console.log(orderId)
       const {data} = await cancalOrders ({orderId})
           this.$message('退款成功');
           console.log(data)
      this.getList()
    },
    // //导出订单列表
    // async exportExcel() {
    //   console.log(this.value)
    // },
    //导出
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['订单编号', '订单状态', '手机号','	用户昵称','充电宝ID', '机柜编号','借用地点','租用时间','归还时间','使用时长','租用费用','优惠券抵扣','积分抵扣','支付方式','实付款']
        const filterVal = ['orderId', 'orderStatus', 'usersPhone','nickName','batteryId', 'equipmentId','businessAddress',
        'leaseStartTime','leaseEndTime','useTime','totalPrice','couponPrice','couponScore','payType','actualPrice']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '订单列表'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
      if (j === 'orderStatus') {
        return v[j]== 1 ? '未支付' : v[j] == 2 ? '进行中' : '已完成'
      } 
      if (j === 'leaseStartTime') {
        return parseTime(v[j]) 
      }
      if (j === 'leaseEndTime') {
        return parseTime(v[j]) 
      }
      if (j === 'payType') {
        return v[j] == 1 ? '余额' :v[j] == 2 ? '微信':v[j] == 3 ?'信用卡':'-'
      } 
      else {
        return v[j]
      }
      }))
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    formatDate(date, offset){
        if(date && typeof date  == 'object' ){
            const d = date[offset];
            return new Date(d).getTime()
        }
        return ''
    },
  },
  computed: {
    filters() {
      return {
        orderId: this.listQuery.orderId,
        batteryId: this.listQuery.batteryId,
        startTime:this.listQuery.date ? this.listQuery.date[0]: '',
        endTime:this.listQuery.date ? this.listQuery.date[1]: '',
        pageNo: this.listQuery.pageNo,
        pageSize: this.listQuery.pageSize,
        userPhone: this.listQuery.usersPhone,
        businessAddress: this.listQuery.address,
        payType: this.listQuery.payType
      }
    },
  },
  created() {
    this.getList()
  },
}
</script>
